use crate::protoHeader::{ProtoHeader, HEADER_SIZE};
use num_traits::FromPrimitive;
use crate::ProtoId::ProtoID;
use serde::Serialize;
use prost::Message;


// use ::prost::Message;
#[derive(Debug, Serialize)]
pub enum ReceiveProtoErr {
    HeaderDeserializationErr,
    BodyProtobuffDeserialErr,
    NeedDeserialize,
    //未处理.有遗漏
    TCPReadSizeWrong(String), //从TCP读取的size 不等于 header size + body size
}


pub fn analyse_header(msg: &[u8], readSize: usize) -> Result<ProtoHeader, ReceiveProtoErr> {
    let header = ProtoHeader::parse(msg, 0).or_else(|e| Err(ReceiveProtoErr::HeaderDeserializationErr))?;
    if HEADER_SIZE + header.nBodyLen as usize != readSize {
        return Err(ReceiveProtoErr::TCPReadSizeWrong(std::fmt::format(format_args!("bodylen:{}, readSize:{}", header.nBodyLen, readSize))));
    }
    Ok(header)
}

// pub fn analyse_body_buffer<T: prost::Message>(header: &ProtoHeader, body_buffer: &[u8]) -> Result<Box<T>, ReceiveProtoErr> {
//     // deserializeBody::<T>(header.nProtoID, body_buffer)
//     let decoded : Result<T, prost::DecodeError> = prost::Message::decode(body_buffer);
//     match decoded {
//         Ok(v) => return Ok(Box::new(v)),
//         Err(e) => return Err(ReceiveProtoErr::BodyProtobuffDeserialErr),
//     }
//     // match FromPrimitive::from_i32(protoId) {
//     //
//     //     Some(ProtoID::QOT_GETKL) => {
//     //
//     //         // let decoded: qot_get_kl::Response = Message::decode(&buf[..]).unwrap();
//     //         match Message::decode(body_bin) {
//     //             Ok(v) => return Ok(Box::new(v)),
//     //             Err(e) => return Err(ReceiveProtoErr::BodyProtobuffDeserialErr),
//     //         }
//     //     }
//     //     _ => Err(ReceiveProtoErr::NeedDeserialize),
//     // }
// }



